﻿using ZXing;
using System;
using Base.Core;
using WpfAi.Core;
using WpfAi.Enum;
using System.Text;
using WpfAi.Model;
using ZXing.QrCode;
using ZXing.Common;
using Brilliants.UI;
using WpfAi.Protocol;
using System.Windows;
using System.Drawing;
using Base.Core.QRCode;
using System.Windows.Input;
using System.Drawing.Printing;
using Brilliants.UI.ControlsEx;

namespace WpfAi.Vm
{
    public class QRCodeWindowVm : VmBase
    {
        #region ___字段___
        BardCodeHooK BarCode = new BardCodeHooK();
        EnumWindowType enumWindowType;
        EnumBoardType enumBoardType;
        PrintDocument pd = new PrintDocument();
        #endregion

        #region ___构造函数___
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="windowType"></param>
        /// <param name="boardType"></param>
        public QRCodeWindowVm(EnumWindowType windowType, EnumBoardType boardType)
        {
            enumWindowType = windowType;
            enumBoardType = boardType;
            Title = windowType == EnumWindowType.Core ? "核心模组" : (windowType == EnumWindowType.Screen ? "触摸显示模组" : "组装模组");
            Title += boardType == EnumBoardType.Board ? " - 单板功能测试" : " - 整机功能测试";
            InitBarCode();
            SingletonProvider<Analysis>.Instance.OnPlate += Instance_OnPlate;
            //if (GlobalEnvironment.WindowType == EnumWindowType.Core && GlobalEnvironment.BoardType == EnumBoardType.Integrate)
            //{
            //    if (OpenSerial())
            //    {
            //        var protocol = new ReadSn();
            //        var sData = protocol.GetByte();
            //        GlobalEnvironment.Serial.SendData(sData, 0, sData.Length);
            //    }
            //}
            InitPrint();
        }
        #endregion

        #region ___绑定属性___
        /// <summary>
        /// 标题
        /// </summary>
        private string m_Title = string.Empty;

        public string Title
        {
            get { return m_Title; }
            set { m_Title = value; OnPropertyChanged(nameof(Title)); }
        }
        /// <summary>
        /// 标题
        /// </summary>
        private string m_ErrorTitle = string.Empty;

        public string ErrorTitle
        {
            get { return m_ErrorTitle; }
            set { m_ErrorTitle = value; OnPropertyChanged(nameof(ErrorTitle)); }
        }
        /// <summary>
        /// PCB二维码
        /// </summary>
        private string m_PCBQRCode = string.Empty;

        public string PCBQRCode
        {
            get { return m_PCBQRCode; }
            set { m_PCBQRCode = value; OnPropertyChanged(nameof(PCBQRCode)); }
        }
        /// <summary>
        /// PCB二维码图片路径
        /// </summary>
        private string m_PCBQRCodePath;

        public string PCBQRCodePath
        {
            get { return m_PCBQRCodePath; }
            set { m_PCBQRCodePath = value; OnPropertyChanged(nameof(PCBQRCodePath)); }
        }
        /// <summary>
        /// 二维码
        /// </summary>
        private string m_ScreenQRCode = string.Empty;

        public string ScreenQRCode
        {
            get { return m_ScreenQRCode; }
            set { m_ScreenQRCode = value; OnPropertyChanged(nameof(ScreenQRCode)); }
        }
        /// <summary>
        /// 二维码图片
        /// </summary>
        private string m_ScreenQRCodePath;

        public string ScreenQRCodePath
        {
            get { return m_ScreenQRCodePath; }
            set { m_ScreenQRCodePath = value; OnPropertyChanged(nameof(ScreenQRCodePath)); }
        }
        /// <summary>
        /// 二维码图片
        /// </summary>
        private string m_PCBCodeTitle = "PCB二维码";

        public string PCBCodeTitle
        {
            get
            {
                if (GlobalEnvironment.WindowType == EnumWindowType.Screen
                    && GlobalEnvironment.BoardType == EnumBoardType.Integrate)
                    return "外壳二维码";
                else
                    return m_PCBCodeTitle;
            }
            set { m_PCBCodeTitle = value; OnPropertyChanged(nameof(PCBCodeTitle)); }
        }
        /// <summary>
        /// 二维码图片
        /// </summary>
        private string m_CameraCodeTitle = "摄像头二维码";

        public string CameraCodeTitle
        {
            get
            {
                if (GlobalEnvironment.WindowType == EnumWindowType.Core)
                    return m_CameraCodeTitle;
                else if (GlobalEnvironment.WindowType == EnumWindowType.Screen && GlobalEnvironment.BoardType == EnumBoardType.Board)
                    return "屏幕二维码";
                else if (GlobalEnvironment.WindowType == EnumWindowType.Assemble && GlobalEnvironment.BoardType == EnumBoardType.Integrate)
                    return "屏幕二维码";
                else
                    return string.Empty;
            }
            set { m_CameraCodeTitle = value; OnPropertyChanged(nameof(CameraCodeTitle)); }
        }
        /// <summary>
        /// 读取SN按钮式否可见
        /// </summary>
        public string ReadVisable
        {
            get
            {
                if (GlobalEnvironment.WindowType == EnumWindowType.Core && GlobalEnvironment.BoardType == EnumBoardType.Integrate)
                    return "Visible";
                else
                    return "Collapsed";
            }
        }
        /// <summary>
        /// 打印按钮式否可见
        /// </summary>
        public string PrintVisable
        {
            get
            {
                if (GlobalEnvironment.WindowType == EnumWindowType.Assemble)
                    //|| (GlobalEnvironment.WindowType == EnumWindowType.Core && GlobalEnvironment.BoardType == EnumBoardType.Integrate))
                    return "Visible";
                else
                    return "Collapsed";
            }
        }
        /// <summary>
        /// 测试按钮是否可见
        /// </summary>
        public string TestVisable
        {
            get
            {
                return GlobalEnvironment.WindowType == EnumWindowType.Assemble ? "Collapsed" : "Visible";
            }
        }
        public string QRCodeVisable
        {
            get
            {
                if (GlobalEnvironment.WindowType == EnumWindowType.Screen
                    && GlobalEnvironment.BoardType == EnumBoardType.Integrate)
                {
                    return "Collapsed";
                }
                else
                    return "Visible";
            }
        }

        #endregion

        #region ___绑定方法___
        /// <summary>
        /// 读取SN
        /// </summary>
        public ICommand ReadSnCommand => new DelegateCommand(o =>
        {
            if (OpenSerial())
            {
                var protocol = new ReadSn();
                var sData = protocol.GetByte();
                GlobalEnvironment.Serial.SendData(sData, 0, sData.Length);
            }
        });
        /// <summary>
        /// 打印SN号码
        /// </summary>
        public ICommand PrintSnCommand => new DelegateCommand(o =>
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    ////////////直接打印/////////////
                    if (GlobalEnvironment.WindowType == EnumWindowType.Core && GlobalEnvironment.BoardType == EnumBoardType.Integrate)
                        PrintSn();
                    ///////////校验绑定关系通过才打印//////////
                    else if (enumWindowType == EnumWindowType.Assemble && enumBoardType == EnumBoardType.Integrate)
                    {
                        var result = 0;
                        var returnMessage = string.Empty;
                        var requestCode = GlobalEnvironment.WindowType == EnumWindowType.Core ? GlobalEnvironment.ScreenQRCode : GlobalEnvironment.PCBQRCode;
                        var table = Base.Core.MesInterface.Gett_SN_BindInfoALLSN(requestCode, out result, out returnMessage);
                        if (null != table && table.Tables[0].Rows[0]["t_ChildSN"].ToString().ToUpper().Equals(GlobalEnvironment.ScreenQRCode.ToUpper()))
                        {
                            PrintSn();
                            int r = 0;
                            UpLoadTestResult(out r);
                            this.ErrorTitle = string.Empty;
                        }
                        else
                        {
                            this.ErrorTitle = "绑定关系出错";
                            return;
                        }
                    }
                });
            });
        });
        #endregion

        #region ___类内方法___
        /// <summary>
        /// 二维码
        /// </summary>
        private void InitBarCode()
        {
            BarCode.ScanerEvent += new BardCodeHooK.ScanerDelegate(Listener_ScanerEvent);
            BarCode.Start();
        }
        /// <summary>
        /// 扫码回调[1、核心板PCB 5MG 2、屏幕PCB 5MH；1、摄像头 5QJ 2、屏幕总成 5QH]
        /// </summary>
        /// <param name="barCode"></param>
        private void Listener_ScanerEvent(BardCodeHooK.ScanerCodes barCode)
        {
            LogHelper.Log.Error("打印发生错误:11223344");
            if (!string.IsNullOrEmpty(barCode.Result))
            {
                if (enumWindowType == EnumWindowType.Core)
                {
                    if (barCode.Result.Contains("5MG"))
                    {
                        if (!this.PCBQRCode.Equals(barCode.Result))
                        {
                            this.ScreenQRCode = string.Empty;
                            this.ScreenQRCodePath = string.Empty;
                            GlobalEnvironment.ScreenQRCode = barCode.Result;
                        }
                        this.PCBQRCode = barCode.Result;
                        this.PCBQRCodePath = QRCodeEncoder.Encode(barCode.Result);
                        GlobalEnvironment.PCBQRCode = barCode.Result;
                    }
                    else if (barCode.Result.Contains("5QJ"))
                    {
                        this.ScreenQRCode = barCode.Result;
                        this.ScreenQRCodePath = QRCodeEncoder.Encode(barCode.Result);
                        GlobalEnvironment.ScreenQRCode = barCode.Result;
                    }
                }
                else if (enumWindowType == EnumWindowType.Screen || enumWindowType == EnumWindowType.Assemble)
                {
                    if (barCode.Result.Contains("5MH"))
                    {
                        if (!this.PCBQRCode.Equals(barCode.Result))
                        {
                            this.ScreenQRCode = string.Empty;
                            this.ScreenQRCodePath = string.Empty;
                            GlobalEnvironment.ScreenQRCode = barCode.Result;
                        }
                        this.PCBQRCode = barCode.Result;
                        this.PCBQRCodePath = QRCodeEncoder.Encode(barCode.Result);
                        GlobalEnvironment.PCBQRCode = barCode.Result;
                    }
                    else if (barCode.Result.Contains("5QH"))
                    {
                        this.ScreenQRCode = barCode.Result;
                        this.ScreenQRCodePath = QRCodeEncoder.Encode(barCode.Result);
                        GlobalEnvironment.ScreenQRCode = barCode.Result;
                    }
                }
            }
        }
        /// <summary>
        /// 下位机上报事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Instance_OnPlate(object sender, ResponseWarp e)
        {
            if (e.Command == StaticCommand.U_ReadSn)
            {
                var sn = Encoding.UTF8.GetString(e.DataBuffer).Substring(0, 14);
                this.PCBQRCode = sn;
                GlobalEnvironment.PCBQRCode = sn;
                this.PCBQRCodePath = QRCodeEncoder.Encode(sn);
            }
        }
        /// <summary>
        /// 打开串口
        /// </summary>
        private bool OpenSerial(bool sleep = false)
        {
            bool r = false;
            try
            {
                GlobalEnvironment.Serial.closePort();
                GlobalEnvironment.Serial.setSerialPort(GlobalEnvironment.Com, GlobalEnvironment.Rate, 8, 1);
                r = GlobalEnvironment.Serial.openPort();
            }
            catch
            {
            }
            return r;
        }
        /// <summary>
        /// 初始化打印机
        /// </summary>
        private void InitPrint()
        {
            pd.DefaultPageSettings.Landscape = false;//设置横向打印，不设置默认是纵向的
            var a = pd.DefaultPageSettings.PrintableArea;
            var b = pd.DefaultPageSettings.PaperSize;

            pd.PrintPage += new PrintPageEventHandler(PrintDocument_PrintPage);
            pd.PrintController = new System.Drawing.Printing.StandardPrintController();
        }
        /// <summary>
        /// 打印SN号码
        /// </summary>
        private void PrintSn()
        {
            if (!string.IsNullOrEmpty(this.PCBQRCode) && !string.IsNullOrEmpty(this.ScreenQRCode))
                pd.Print();
        }
        /// <summary>
        /// 打印机事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            var w = e.PageSettings.PaperSize.Width;
            var h = e.PageSettings.PaperSize.Height;

            e.PageSettings.Margins = new Margins() { Left = 2, Right = 0, Top = 0, Bottom = 0 };
            Font titleFont = new Font("宋体", 4, System.Drawing.FontStyle.Bold);//标题字体           
            System.Drawing.Brush brush = new SolidBrush(System.Drawing.Color.Black);//画刷     
            try
            {
                ///////////////打印图片/////////////
                Bitmap bitmap = CreateQRCode(this.PCBQRCode);
                e.Graphics.DrawImage(bitmap, new Rectangle() { X = 70, Y = 0, Width = 20, Height = 20 });
                ////////////////打印文字////////////
                e.Graphics.DrawString(this.PCBQRCode.Substring(0, 7), titleFont, brush, new Rectangle() { X = 88, Y = 5, Width = 30, Height = 24 }, new StringFormat() { FormatFlags = StringFormatFlags.MeasureTrailingSpaces });
                ////////////////打印文字////////////
                e.Graphics.DrawString(this.PCBQRCode.Substring(7, 7), titleFont, brush, new Rectangle() { X = 88, Y = 12, Width = 26, Height = 24 });
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error("打印发生错误:" + ex.Message);
            }
        }
        /// <summary>
        /// 生成二维码位图
        /// </summary>
        /// <param name="asset"></param>
        /// <returns></returns>
        public Bitmap CreateQRCode(string asset)
        {
            EncodingOptions options = new QrCodeEncodingOptions
            {
                DisableECI = true,
                CharacterSet = "UTF-8", //编码
                Width = 5,             //宽度
                Height = 5             //高度
            };
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;
            writer.Options = options;
            return writer.Write(asset);
        }
        /// <summary>
        /// 上传测试结果
        /// </summary>
        private void UpLoadTestResult(out int result)
        {
            var requestCode = GlobalEnvironment.WindowType == EnumWindowType.Core ? GlobalEnvironment.ScreenQRCode : GlobalEnvironment.PCBQRCode;
            Base.Core.MesInterface.UploadResult(requestCode, "1", "0", GlobalEnvironment.GetStationID(), out result);
        }
        #endregion
    }
}